//
//  EPCStatusListViewModel.swift
//  Weibo
//
//  Created by LioWu on 08/04/2017.
//  Copyright © 2017 MyGit. All rights reserved.
//

import Foundation
import YYModel

// pull up max try times count
private let maxPullUpTryTimes = 3

class EPCStatusListViewModel {
    
    lazy var statusList = [EPCStatus]()
    
    private var pullErrorTimes = 0
    
    
    /// load status datas
    ///
    /// - Parameters:
    ///   - isPullUp: is pull up. default is false, mean pull down
    ///   - completion: closure（ 1.request is success, 2.should refresh datas）
    func loadStatus(isPullUp:Bool = false, completion:@escaping (_ isSuccess:Bool, _ shouldRefresh:Bool)->()) {
        
        if isPullUp && pullErrorTimes >= maxPullUpTryTimes {
            completion(true, false)
            return
        }
        
        var since_id:Int64 = 0
        var max_id:Int64 = 0
        
        if isPullUp == false {
            since_id = statusList.first?.id ?? Int64(0)
        }
        else {
            max_id = statusList.last?.id ?? Int64(0)
        }
    
        
        EPCNetworking.shareManager.statusList(since_id: since_id, max_id: max_id) { (result, isSuccess) in
            
            guard let list = NSArray.yy_modelArray(with: EPCStatus.self, json: result ?? []) as? [EPCStatus] else {
                
                completion(isSuccess, false)
                
                return
            }
            
            print("刷新到\(list.count)条")
            
            if isPullUp == false {
                self.statusList = list + self.statusList
            } else {
                self.statusList = self.statusList + list
            }
            
            if isPullUp == true && list.count == 0 {
                
                self.pullErrorTimes += 1
                
                completion(isSuccess, false)
                
            } else {
                
                completion(isSuccess, true)
            }
            
        }
    }
    
}
